<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Grid;
use App\Models\Project;
use Dcat\Admin\Widgets\Card;
use Dcat\Admin\Admin;
use App\Models\Cabinet;
use App\Models\CabinetDataSecond as CabinetData;
use App\Models\CabinetPoint;
use Illuminate\Http\Request;

class CabinetDataSecondController extends Controller
{
    protected $pageSize = 3600;

    public function history(Content $content, $id = 0)
    {   
        Admin::css('/layui/css/layui.css');
        
        $id = json_decode($id,true);
        if (is_array($id) && !empty($id)) {    //监测点
            $checkedPoints = $id;
            //如果跨柜子，默认只取第一个
            $tmp = explode('-', reset($checkedPoints));
            $firstId = reset($tmp);
            foreach ($checkedPoints as $k => $v) {
                if (strpos($v, $firstId.'-') === false) {
                    unset($checkedPoints[$k]);
                }
            }
            $treeCard = $this->historyMenuTree($checkedPoints);
        } else {    //盒子id
            if (empty($id)) {
                $id = session('tmpbox');
            } else {
                session()->put('tmpbox', $id);
            }
            $treeCard = $this->historyMenuTree($id);
            $checkedPoints = null;
        }
        return $content
            ->header('历史记录')
            ->description('')
            ->body(function (Row $row) use ($checkedPoints, $treeCard) {
                $row->column(2, $treeCard);
                if ($checkedPoints) {
                    $row->column(10, function (Column $column) use ($checkedPoints) {
                        foreach ($checkedPoints as $oneCheckedPoint) {
                            $info = explode('-',$oneCheckedPoint);
                            $cabinetId = reset($info);
                            $alias = end($info);
                            $cabinets[$cabinetId][] = $alias;
                        }
                        $cabinet = Cabinet::find($cabinetId);
                        $fields = reset($cabinets);      
                        $column->row(function(Row $row) use ($cabinet, $fields) {
                            $row->column(12, '<div style="text-align: center; font-size: 22px;margin: 20px">'.$cabinet['name'].'</div>');
                        });
                        $column->row($this->historyGrid($cabinet, $fields));
                    });
                }
                    
            });
        }

    protected function historyMenuTree($checkedIds = null){
        if (is_array($checkedIds)) {
            $info = explode('-',reset($checkedIds));
            $cabinetId = reset($info);
            $cabinet = Cabinet::find($cabinetId);
            $projectId = $cabinet['project_id'];
            $pid = $cabinet['pid'];
        } else {
            $cabinet = Cabinet::find($checkedIds);
            $projectId = $cabinet['project_id'];
            $pid = $cabinet['id'];
        }

        $menu = [];
        $cabinets = Cabinet::select(['id', 'name', 'pid'])->where('project_id', $projectId)->get()->toArray();

        foreach ($cabinets as $k => $v) {
            if (!$v['pid']) {
                if ($v['id'] == $pid) {
                    $one['spread'] = true;
                } else {
                    $one['spread'] = false;
                }
                $one['title'] = $v['name'];
                $one['id'] = $v['id'];
                $one['children'] = [];
                $one['isParent'] = true;
                $one['url'] = url('admin/cabinet-realtime').'/'.$projectId."/".$v['id'];
                foreach ($cabinets as $kk => $vv) {
                    if ($v['id'] == $vv['pid']) {
                        if ($vv['id'] == $cabinet['id']) {
                            $children['spread'] = true;
                        } else {
                            $children['spread'] = false;
                        }
                        $children['title'] = $vv['name'];
                        $children['id'] = $vv['id'];
                        $children['url'] = url('admin/cabinet-realtime-detail').'/'.$projectId.'/'.$vv['id'];
                        
                        $children['children'] = [];
                        $points = CabinetPoint::where('cabinet_id', $vv['id'])->where('history_show', 1)->get()->toArray();
                        if ($points) {
                            foreach ($points as $key => $onePoint) {
                                $c['spread'] = false;
                                $c['title'] = $onePoint['name'];
                                $c['id'] = $vv['id'].'-'.$onePoint['alias'];
                                array_push($children['children'], $c);
                            }
                        }
                        array_push($one['children'], $children);
                    }
                }
            array_push($menu, $one);
            }
        }

        if ($checkedIds && is_array($checkedIds)) {
            $data['checkedIds'] = json_encode($checkedIds);
        } else {
            $data['checkedIds'] = json_encode([]);
        }

        $data['menu'] = json_encode($menu);
        $card = Card::make(view('admin.cabinet.historyMenuTreeSecond', $data));
        return $card;
    }

    protected function historyGrid($cabinet, $fields){
        $aliasNames = CabinetPoint::where('cabinet_id', $cabinet['id'])->pluck('name','alias')->toArray();
        $m = CabinetData::select(['data', 'created_time'])->where('cabinet_id', $cabinet['id'])->orderBy('created_time', 'desc');
        return Grid::make($m, function (Grid $grid) use ($fields, $aliasNames) {
            $grid->setActionClass(Grid\Displayers\Actions::class);
            $grid->column('created_time','上报时间');
            $grid->column('created_time','上报时间')->display(function ($time) {
                return date("Y-m-d H:i:s", $time);
            });

            foreach ($fields as $alias) {
                $grid->column($alias, $aliasNames[$alias])->display(function ($v) use($alias) {
                    return json_decode($this->data, true)[$alias];
                });
            }

            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->disableViewButton();

            $grid->showFilter();
            $grid->showFilterButton();
            $grid->filter(function($filter){
                // 展开过滤器
                $filter->panel();
                $filter->between('created_time', '上报时间')->datetime()->toTimestamp();
            });
            // $grid->export();
            $grid->export()->rows(function (array $rows) use($fields) {
                foreach ($rows as $index => &$row) {
                    $row['created_time'] = date("Y-m-d H:i:s", $row['created_time']);
                    foreach ($fields as $alias) {
                        $row[$alias] = json_decode($row['data'], true)[$alias];
                    }
                }
                return $rows;
            });
            $grid->export()->filename('历史数据-'.time());
        });
    }

    public function destroy($idx, $id){
        $form = Form::make(new CabinetData(), function (Form $form) {});
        return $form->destroy($id);
    }


    public function historyLine(Content $content, $id = 0)
    {
        Admin::css('/layui/css/layui.css');

        if (strpos($id, '-') === false) {
            $cabinet = Cabinet::find($id);
            return $content
            ->header($cabinet['name'])
            ->description()
            ->body(function (Row $row) use ($cabinet) {
                $row->column(2, $this->historyLineTree($cabinet));
            });
        } else {
            $info = explode('-', $id);
            $cabinetId = reset($info);
            $alias = end($info);
            $cabinet = Cabinet::find($cabinetId);
            $point = CabinetPoint::where('cabinet_id', $cabinetId)->where('alias', $alias)->value('name');
            return $content
                ->header($cabinet['name'].'-'.$point)
                ->description()
                ->body(function (Row $row) use ($cabinet, $alias, $point) {
                    $row->column(2, $this->historyLineTree($cabinet));
                    $row->column(10, function (Column $column) use ($cabinet, $alias, $point) {
                        $column->row(function(Row $row) use ($cabinet, $alias, $point) {
                            $row->column(12, '<div style="text-align: center; font-size: 22px;margin: 20px">'.$cabinet['name'].'-'.$point.'</div>');
                        });
                        $column->row($this->historyLineChart($cabinet, $alias));
                    });
                });
        }
    }

    protected function historyLineTree($cabinet){
        $projectId = $cabinet['project_id'];

        $cabinets = Cabinet::select(['id', 'name', 'pid'])->where('project_id', $projectId)->get()->toArray();
        $menu = [];
        //盒子
        foreach ($cabinets as $k => $v) {
            if (!$v['pid']) {
                $one['spread'] = true;
                $one['title'] = $v['name'];
                $one['id'] = $v['id'];
                $one['children'] = [];
                $one['isParent'] = true;
                // $one['url'] = url('admin/cabinet-realtime').'/'.$projectId.'/'.$v['id'];
                $one['url'] = '';
                //设备(电源柜)
                foreach ($cabinets as $kk => $vv) {
                    if ($v['id'] == $vv['pid']) {
                        if ($vv['id'] == $cabinet['id']) {
                            $children['spread'] = true;
                        } else {
                            $children['spread'] = false;
                        }
                        $children['title'] = $vv['name'];
                        $children['id'] = $vv['id'];
                        $children['isParent'] = true;
                        // $children['url'] = url('admin/cabinet-realtime-detail').'/'.$projectId.'/'.$vv['id'];
                        $children['url'] = '';
                        $children['children'] = [];
                        $points = CabinetPoint::where('cabinet_id', $vv['id'])->pluck('name', 'alias')->toArray();
                        //采集点
                        foreach ($points as $key => $value) {
                            $c['spread'] = true;
                            $c['title'] = $value;
                            $c['id'] = $vv['id'].'-'.$key;
                            $c['url'] = url('admin/cabinet-history-line-second').'/'.$c['id'];
                            array_push($children['children'], $c);
                        }
                        array_push($one['children'], $children);
                    }
                }
            array_push($menu, $one);
            }
        }
        $data['menu'] = json_encode($menu);
        $card = Card::make(view('admin.cabinet.monitorMenuTree', $data));
        return $card;
    }

    protected function historyLineChart($cabinet, $alias){
        // $start = strtotime(date("Y-m-d"));
        $start = strtotime("-24 hour");
        $end = time();

        $page = 1;
        $d = CabinetData::getJsonDataListPaging($cabinet['id'], $alias, $start, $end, $page, $this->pageSize);
        $xData = [];
        $yData = [];
        foreach ($d as $one) {
            $one = json_decode( json_encode( $one ),true);
            $xData[] = date("H:i:s", $one['created_time']);
            $yData[] = $one[$alias];
        }
        $data['cabinet'] = $cabinet;
        $data['alias'] = $alias;
        if ($d) {
            $endPoint = json_decode( json_encode( end($d) ),true);
            $data['endX'] = $endPoint['created_time'];
        } else {
            $data['endX'] = time();
        }
        $data['xData'] = json_encode($xData);
        $data['yData'] = json_encode($yData);
        $data['currentPage'] = $page;
        $data['currentTotal'] = count($d);
        $data['pageSize'] = $this->pageSize;
        $data['start'] = $start;
        $data['end'] = $end;


        $card = Card::make(view('admin.cabinet.historyLineChartSecond', $data));
        return $card;
    }

    public function getHistoryLineChartPage(Request $request){
        $param = $request->all();
        $page = $param['page'] + 1;


        $d = CabinetData::getJsonDataListPaging($param['cabinetId'], $param['alias'], $param['start'], $param['end'], $page, $this->pageSize);

        if ($d) {
            $xData = [];
            $yData = [];
            foreach ($d as $one) {
                $one = json_decode( json_encode( $one ),true);
                $xData[] = date("H:i:s", $one['created_time']);
                $yData[] = $one[$param['alias']];
            }
            $data['xData'] = $xData;
            $data['yData'] = $yData;
            $endPoint = json_decode( json_encode( end($d) ),true);
            $data['endX'] = $endPoint['created_time'];

            $data['currentPage'] = $page;
            $data['currentTotal'] = count($d);
            $data['pageSize'] = $this->pageSize;
            $data['start'] = $param['start'];
            $data['end'] = $param['end'];

            return response()->json(['code'=>1, 'data' => $data, 'msg' => 'success']);
        } else {
            return response()->json(['code'=>0, 'data' => $data, 'msg' => 'no update']);
        }
    }

    public function getHistoryLineChart(Request $request){
        $param = $request->all();
        $time = strtotime(date("Y-m-d")." ". $param['endX']. ":00");

        $d = CabinetData::getJsonDataList($param['cabinetId'], $param['alias'], $param['endX']);
        if ($d) {
            $xData = [];
            $yData = [];
            foreach ($d as $one) {
                $one = json_decode( json_encode( $one ),true);
                $xData[] = date("H:i:s", $one['created_time']);
                $yData[] = $one[$param['alias']];
            }
            $data['xData'] = $xData;
            $data['yData'] = $yData;
            $endPoint = json_decode( json_encode( end($d) ),true);
            $data['endX'] = $endPoint['created_time'];
            return response()->json(['code'=>1, 'data' => $data, 'msg' => 'success']);
        } else {
            return response()->json(['code'=>0, 'data' => [], 'msg' => 'no update']);
        }
    }

    //*****************************************************
    //*****************************************************
    public function compare(Content $content, $id = 0)
    {       
        Admin::css('https://www.layuicdn.com/layui/css/layui.css');
        $id = json_decode($id,true);
        if (is_array($id) && !empty($id)) {    //监测点
            $checkedPoints = $id;
            $treeCard = $this->compareMenuTree($checkedPoints);
        } else {    //盒子id
            if (empty($id)) {
                $id = session('tmpbox');
            } else {
                session()->put('tmpbox', $id);
            }
            $treeCard = $this->compareMenuTree($id);
            $checkedPoints = null;
        }

        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $compareDate = session('compare_date') ? session('compare_date') : $yesterday;
        return $content
            ->header('历史曲线')
            ->description(view('admin.cabinet.compareDateSelect',['compareDate' => $compareDate]))
            ->body(function (Row $row) use ($treeCard, $checkedPoints) {
                $row->column(2, $treeCard);
                if (is_array($checkedPoints) && !empty($checkedPoints)) {
                    $cabinets = [];
                    foreach ($checkedPoints as $oneCheckedPoint) {
                        $info = explode('-',$oneCheckedPoint);
                        $cabinetId = reset($info);
                        $alias = end($info);
                        $cabinets[$cabinetId][] = $alias;
                    }
                    $row->column(10, function (Column $column) use ($cabinets) {
                        $column->row(function(Row $row) use ($cabinets) {
                            foreach ($cabinets as $id => $points) {
                                $row->column(12, $this->compareChart($id, $points));
                            }
                        });
                    });
                }
            });
    }

    protected function compareMenuTree($checkedIds = null){
        if (is_array($checkedIds)) {
            $info = explode('-',reset($checkedIds));
            $cabinetId = reset($info);
            $cabinet = Cabinet::find($cabinetId);
            $projectId = $cabinet['project_id'];
            $pid = $cabinet['pid'];
        } else {
            $cabinet = Cabinet::find($checkedIds);
            $projectId = $cabinet['project_id'];
            $pid = $cabinet['id'];
        }

        $cabinets = Cabinet::select(['id', 'name', 'pid'])->where('project_id', $projectId)->get()->toArray();
        $menu = [];

        foreach ($cabinets as $k => $v) {
            if (!$v['pid']) {
                if ($v['id'] == $pid) {
                    $one['spread'] = true;
                } else {
                    $one['spread'] = false;
                }
                $one['title'] = $v['name'];
                $one['id'] = $v['id'];
                $one['children'] = [];
                $one['isParent'] = true;
                foreach ($cabinets as $kk => $vv) {
                    if ($v['id'] == $vv['pid']) {
                        if ($vv['id'] == $cabinet['id']) {
                            $children['spread'] = true;
                        } else {
                            $children['spread'] = false;
                        }
                        $children['title'] = $vv['name'];
                        $children['id'] = $vv['id'];
                        $children['children'] = [];
                        $points = CabinetPoint::where('cabinet_id', $vv['id'])->where('history_line_show', 1)->get()->toArray();
                        if ($points) {
                            foreach ($points as $key => $onePoint) {
                                $c['spread'] = false;
                                $c['title'] = $onePoint['name'];
                                $c['id'] = $vv['id'].'-'.$onePoint['alias'];
                                array_push($children['children'], $c);
                            }
                        }
                        array_push($one['children'], $children);
                    }
                }
            array_push($menu, $one);
            }
        }

        if ($checkedIds && is_array($checkedIds)) {
            $data['checkedIds'] = json_encode($checkedIds);
        } else {
            $data['checkedIds'] = json_encode([]);
        }
        $data['menu'] = json_encode($menu);
        $card = Card::make(view('admin.cabinet.compareTreeSecond', $data));
        return $card;
    }

    protected function compareChart($cabinetId, $points){
        $cabinet = Cabinet::find($cabinetId);
        $aliasNames = CabinetPoint::where('cabinet_id', $cabinetId)->whereIn('alias', $points)->pluck('name','alias')->toArray();

        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $date = session('compare_date') ? session('compare_date') : $yesterday;

        $start = strtotime($date);
        $end = strtotime("+1 day", $start);

        $d = CabinetData::getJsonDataList($cabinetId, $points, $start, $end);

        if (empty($d)) {
            $card = Card::make('暂无数据');
            return $card;
        }

        foreach ($d as $one) {
            $one = json_decode( json_encode( $one ),true);
            $xData[] = date("H:i:s", $one['created_time']);
            foreach ($points as $onePoint) {
                $$onePoint[] = $one[$onePoint];
            }
        }

        $legend = [];
        $series = [];
        foreach ($points as $onePoint) {
            $legend[] = $aliasNames[$onePoint];
            
            $oneSeries['name'] = $aliasNames[$onePoint];
            $oneSeries['type'] = 'line';
            //$oneSeries['stack'] = 'Total';
            $oneSeries['data'] = $$onePoint;
            array_push($series, $oneSeries);
        }

        $data['xData'] = json_encode($xData);
        $data['series'] = json_encode($series);
        $data['legend'] = json_encode($legend);
        $data['cabinet'] = $cabinet;
        $data['startValue'] = date("H:i", strtotime("-1 hours", $end));

        $card = Card::make(view('admin.cabinet.compareChartSecond', $data));
        return $card;
    }

}
